package com.moli.iov.handle.worker.his.util;

import com.moli.iov.handle.worker.his.hbase.IHbaseService;
import com.moli.iov.handle.worker.his.lmax.DisruptorTask;
import com.moli.iov.handle.worker.his.mongodb.Mongo;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

/**
 * Coroutine real time message handle Task for disruptor.
 *
 * @author OAK
 * @since 2020/01/16 16:46 PM.
 * @version 3.0.1
 *
 */
@Slf4j
@Component("realtimeHandler")
public class RealtimeHandler implements DisruptorTask {

    /**
     * HBase real time message of family.
     */
    @Value("${hbase.table.family}")
    private  String family;

    /**
     * HBase real time message of table name.
     */
    @Value("${hbase.tableName.iov.realtime}")
    private  String tableName;

    /**
     * HBase service.
     */
    @Resource
    private IHbaseService iHbaseService;

    /**
     * Mongo service.
     */
    @Resource
    private Mongo mongoService;

    private static final String realTimeMessage = "realtimeMessage";

    private static final String realTimeMessageUniquePropertyName = "rowKey";

    /**
     * Real time message handle for disruptor.
     * @param params Handle params.
     */
    @Override
    public void subscribe(Object params) {
        ConcurrentMap<String, Map<String, Object>> concurrentMap = (ConcurrentMap<String, Map<String, Object>>) params;
        Boolean flag = false;
        try {
            flag = iHbaseService.save(tableName, family, concurrentMap);
        }catch (Exception ex){
            log.error("Query HBase found exception, cause:", ex);
        }
//        if(flag){
//            Set<String> keys = concurrentMap.keySet();
//            Set<String> ne = mongoService.find(realTimeMessage, keys );
//            keys.removeAll(ne);
//            if(!keys.isEmpty()){
//                List<Document> realtimeMessageCollection =
//                        keys.stream().map(k -> new Document().append(realTimeMessageUniquePropertyName, k))
//                                .collect(Collectors.toList());
//                mongoService.saveAll(realTimeMessage, realtimeMessageCollection);
//            }
//        }
    }
}